<template>
  <div
    ref="myChart"
    :class="props.className"
    :style="{
      width: props.width,
      height: props.height
    }"
  ></div>
</template>
<script lang="ts" setup>
  import { defineProps, onMounted, onUnmounted, ref, watch } from 'vue'
  import * as echarts from 'echarts'
  type EChartsOption = echarts.EChartsOption
  type PropsType = {
    // 图表类名
    className: {
      type: String
      default: 'charts'
    }
    // 图表宽度
    width: {
      type: String
      require: true
    }
    // 图表高度
    height: {
      type: String
      require: true
    }
    // 图表数据项
    options: {
      type: Object
      default: () => {}
    }
  }
  const props = defineProps<PropsType>()
  const myChart = ref<HTMLElement>() //也可以用const myChart = ref<any>();
  const myCharts = ref()

  const initChart = (data?: EChartsOption, clearCaching = true) => {
    if (data || props.options) {
      myCharts.value.setOption(data || props.options, clearCaching)
    }
  }
  watch(
    () => props.options,
    (val) => {
      if (myChart.value) {
        initChart()
      }
    }
  )
  // mounted
  onMounted(() => {
    myCharts.value = echarts.init(myChart.value!)
    initChart()
  })

  onUnmounted(() => {
    myCharts.value = null
  })
</script>
<style lang="scss" scoped></style>
